package com.moore.net;


import com.moore.utils.WebUtils;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Map;

public class HttpResponse {
    private final HttpRequest httpRequest;
    private final OutputStream outputStream;
    private final PrintWriter printWriter;
    private String responseData;

    public HttpResponse(HttpRequest httpRequest, Socket socket) {
        this.httpRequest = httpRequest;
        try {
            this.outputStream = socket.getOutputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        this.printWriter = new PrintWriter(new OutputStreamWriter(this.outputStream));
    }

    // 发送响应行
    public void responseLine(){
        responseData = httpRequest.getProtocol() + " " + 200 + " " + "OK" + "\r\n";
        socketPrint();
    }

    // 发送响应头
    public void responseHeader(byte[] fileData){
        // 调用映射方法获取扩展名对应的 MIME类型
        Map<String, String> mimeTypes = WebUtils.getMimeTypes();
        // 获取文件的扩展名
        String filename = "html" + httpRequest.getUrl();
        String extension = "";
        int i = filename.lastIndexOf('.');
        if (i > 0) {
            extension = filename.substring(i + 1);
        }
        // 根据扩展名设置Content-Type（若没有对应扩展名，使用默认值）
        String contentType = mimeTypes.getOrDefault(extension, "application/octet-stream");
        // 设置Content-Type
        responseData = "Content-Type: " + contentType + ";charset=utf-8\r\n";
        socketPrint();
        // 设置Content-Length
        responseData = "Content-Length: " + fileData.length + "\r\n";
        socketPrint();
    }

    // 发送响应空行
    public void responseBlankLine(){
        responseData = "\r\n";
        socketPrint();
    }

    // 发送响应体
    public void responseBody(byte[] fileData){
        try {
            outputStream.write(fileData);
            outputStream.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void socketPrint(){
        printWriter.print(responseData);
        printWriter.flush();
    }
}
